package com.example.ui.contact.chat;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.net.NetContact;
import com.example.ui.LoginActivity;
import com.example.ui.MainActivity;
import com.example.ui.WelcomeActivity;
import com.example.ui.contact.AddFriendActivity;
import com.example.ui.contact.AtMeActivity;
import com.example.ui.contact.CommentMeActivity;
import com.example.ui.contact.MsgState;
import com.example.ui.contact.NoticeActivity;
import com.example.ui.contact.PraiseMeActivity;
import com.example.ui.contact.bean.ChatMsgItem;
import com.example.ui.contact.bean.CommentItem;
import com.example.ui.contact.bean.MeItem;
import com.example.ui.contact.bean.NoticeItem;
import com.example.ui.contact.bean.PraiseItem;
import com.example.ui.contact.bean.RecentItem;
import com.example.ui.contact.bean.RequestItem;
import com.example.ui.contact.bean.User;
import com.example.ui.leftmenu.Item08View;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;




public class PushMessageReceiver extends BroadcastReceiver {
	public static final String TAG = PushMessageReceiver.class.getSimpleName();
	public static final int NOTIFY_ID = 0x000;
	public static int mNewNum = 0;// 通知栏新消息条目，我只是用了一个全局变量，
	public static final String RESPONSE = "response";
	public static ArrayList<EventHandler> ehList = new ArrayList<EventHandler>();		
	public static ArrayList<EventHandler> ehList_Notice = new ArrayList<EventHandler>();             //系统通知数组容器
	public static ArrayList<EventHandler> ehList_Me = new ArrayList<EventHandler>();			     //提到我的数组容器	
	public static ArrayList<EventHandler> ehList_Funs = new ArrayList<EventHandler>();			     //赞数组容器	
	public static ArrayList<EventHandler> ehList_Comment = new ArrayList<EventHandler>();			 //评论数组容器	
	public static ArrayList<EventHandler> ehList_Friend = new ArrayList<EventHandler>();			 //好友请求数组容器	
	public static ArrayList<EventHandler> ehList_Recent = new ArrayList<EventHandler>();			 //私信消息数组容器	
	public static ArrayList<EventHandler> ehList_Chat = new ArrayList<EventHandler>();			     //聊天对话消息数组容器	
	public static ArrayList<EventHandler> ehList_Fd_List = new ArrayList<EventHandler>();            //好友列表数组容器
                                                                     
	public static int MSG_TYPE = 0;  //记录消息类型变量                    
	public static int MSG_TOTAL =0;  //记录消息数目变量
	
	public static int MSG_NOTICE = 0;//系统通知数量
	public static int MSG_ME = 0;//提到我的数量
	public static int MSG_COMMENT = 0;	//评论数量
	public static int MSG_FUNS= 0;//赞数量
	public static int MSG_FRIEND = 0;//好友请求数量
	public static int MSG_CHAT = 0;//私信消息数量
	public static int [] MSG_NUM ={MSG_NOTICE,MSG_ME,MSG_COMMENT,MSG_FUNS};
	
	public Class []obj = {NoticeActivity.class,AtMeActivity.class,CommentMeActivity.class,                      
			              PraiseMeActivity.class,AddFriendActivity.class,ChatActivity.class};
	public static String [] TYPE_STR = {"系统通知","提到我的","评论","赞","好友请求","私信消息"};
	
	
	public static List<Map<String, Object>> MsgList;
	
	/**
	 * 推送消息的类型常量标志
	 */
	public static final int NEW_MESSAGE_STATE = 1;
	//public static int state = -1;
	public static int TYPE_PARA = -1;
	public static final int NOTIFY_MSG_PARA = 0x001;  //系统通知，做通知另外处理
	public static final int ME_MSG_PARA = 0X002;      //提到我的
	public static final int COMMENT_MSG_PARA = 0x003; //评论
	public static final int FUNS_MSG_PARA = 0x004;	  //赞
	public static final int CHAT_MSG_PARA = 0x005;    //私信消息
	public static final int REQUEST_MSG_PARA = 0x006; //好友请求
	public static int [] MSG_INT ={ME_MSG_PARA,COMMENT_MSG_PARA,FUNS_MSG_PARA};
	public static String [] MSG_STR ={"Mention","comment","funs","systemNotifications","friendmsg","msg"};
	
	public static boolean isMsg = false;             //检查是消息的类型是否符合规则
	public static boolean isPush = false;
	public static String type = "message";           //消息类型
	public static CharSequence tickerText =  "最新";
	public static abstract interface EventHandler {
		public abstract void onMessage(String message);

		public abstract void onBind(String method, int errorCode, String content);

		public abstract void onNotify(String title, String content);

		public abstract void onNetChange(boolean isNetConnected);

	}
	
	
	public static Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if(msg.what == NEW_MESSAGE_STATE){
				String message = (String) msg.obj;
				L.Debug("MsgState.state", ""+MsgState.state);  
				L.Debug("MsgState.push_state", ""+MsgState.push_state);  
				switch(MsgState.push_state){//MsgState.state
				case MsgState.REQUEST_MSG_STATE:
					if(ehList_Friend.size()>0&&isMsg&&type.equals(MSG_STR[4])&&isMatch()){//
						for (int i = 0; i < ehList_Friend.size(); i++)
							ehList_Friend.get(i).onMessage(message);			
					}					
					break;
				case MsgState.RECENT_MSG_STATE:
                    L.Debug("MsgState.RECENT_MSG_STATE run", "");
                    L.Debug("MsgState.RECENT_MSG_STATE hList_Recent.size()", ""+ehList_Recent.size());
					if(ehList_Recent.size()>0&&isMsg&&type.equals(MSG_STR[5])){
						
						for (int i = 0; i < ehList_Recent.size(); i++){
							ehList_Recent.get(i).onMessage(message);			
						}
					}
					break;
				case MsgState.NOTICE_MSG_STATE:
					if(ehList_Notice.size()>0&&isMsg&&type.equals(MSG_STR[3])){
					for (int i = 0; i < ehList_Notice.size(); i++)
						ehList_Notice.get(i).onMessage(message);
					}	
					break;
				case MsgState.ME_MSG_STATE:
					if(ehList_Me.size()>0&&isMsg&&type.equals(MSG_STR[0])){
					for (int i = 0; i < ehList_Me.size(); i++){
						
						ehList_Me.get(i).onMessage(message);			
					}
				    }					
					break;
				case MsgState.FUNS_MSG_STATE:
					if(ehList_Funs.size()>0&&isMsg&&type.equals(MSG_STR[2])){
					for (int i = 0; i < ehList_Funs.size(); i++){						
						ehList_Funs.get(i).onMessage(message);
					}
                    }					
					break;
				case MsgState.COMMENT_MSG_STATE:
					if(ehList_Comment.size()>0&&isMsg&&type.equals(MSG_STR[1])){
					for (int i = 0; i < ehList_Comment.size(); i++)
						ehList_Comment.get(i).onMessage(message);			
				    }					
					break;
				case MsgState.CHAT_MSG_STATE:
					if(ehList_Chat.size()>0&&MsgState.state ==MsgState.CHAT_MSG_STATE){//&&isMsg&&type.equals(MSG_STR[5])
					for (int i = 0; i < ehList_Chat.size(); i++){						
						ehList_Chat.get(i).onMessage(message);
					}
					}
					if(ehList_Recent.size()>0&&MsgState.state ==MsgState.RECENT_MSG_STATE){
						
						for (int i = 0; i < ehList_Recent.size(); i++){
							ehList_Recent.get(i).onMessage(message);			
						}
					}
					break;	
				case MsgState.FD_LIST_MSG_STATE:
					L.Debug("push state", String.valueOf(MsgState.FD_LIST_MSG_STATE));
					if(ehList_Fd_List.size()>0&&isMsg&&type.equals(MSG_STR[4])&&isMatch()){
						for(int i = 0;i<ehList_Fd_List.size();i++){
							ehList_Fd_List.get(i).onMessage(message);
						}
					}
					break;
					
					//				case MsgState.MAIN_MSG_STATE:
					//					if(type.equals(MSG_STR[0])){ PushMessageReceiver.MSG_ME++; }
					//					if(type.equals(MSG_STR[1])){ PushMessageReceiver.MSG_COMMENT++; }
					//					if(type.equals(MSG_STR[2])){ PushMessageReceiver.MSG_FUNS++; }	
					//					if(type.equals(MSG_STR[3])){ PushMessageReceiver.MSG_NOTICE++; }		
					//					if(type.equals(MSG_STR[4])){ PushMessageReceiver.MSG_FRIEND++; }	
					//					if(type.equals(MSG_STR[5])){ PushMessageReceiver.MSG_CHAT++; }
					//					if(ehList.size()>0&&isMsg){
					//					for (int i = 0; i < ehList.size(); i++){						
					//						ehList.get(i).onMessage(message);
					//					}
					//					}						
					//					break;
					
					
				default:
						if(type.equals(MSG_STR[0])){ PushMessageReceiver.MSG_ME++; }
						if(type.equals(MSG_STR[1])){ PushMessageReceiver.MSG_COMMENT++; }
						if(type.equals(MSG_STR[2])){ PushMessageReceiver.MSG_FUNS++; }	
						if(type.equals(MSG_STR[3])){ PushMessageReceiver.MSG_NOTICE++; }		
						if(type.equals(MSG_STR[4])){ PushMessageReceiver.MSG_FRIEND++; }	
						if(type.equals(MSG_STR[5])){ PushMessageReceiver.MSG_CHAT++; }		
						// 通知栏提醒，保存数据库
						 if(isMsg){
							 L.Debug("MsgState.showNotify", "ok");  
							
							 //MsgHandle(message);
						 }
				}
			}
		}
	};
	


	@Override
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
			// 获取消息内容
			String message = intent.getExtras().getString(
					PushConstants.EXTRA_PUSH_MESSAGE_STRING);
			// 消息的用户自定义内容读取方式
			L.i("onMessage: " + message);
			L.Debug("push onMessage: ", message);

			Parse(message);// 预处理，过滤一些消息，比如说新人问候或自己发送的

		} else if (intent.getAction().equals(PushConstants.ACTION_RECEIVE)) {
			// 处理绑定等方法的返回数据
			// PushManager.startWork()的返回值通过PushConstants.METHOD_BIND得到
			// 获取方法
			final String method = intent
					.getStringExtra(PushConstants.EXTRA_METHOD);
			// 方法返回错误码。若绑定返回错误（非0），则应用将不能正常接收消息。
			// 绑定失败的原因有多种，如网络原因，或access token过期。
			// 请不要在出错时进行简单的startWork调用，这有可能导致死循环。
			// 可以通过限制重试次数，或者在其他时机重新调用来解决。
			final int errorCode = intent
					.getIntExtra(PushConstants.EXTRA_ERROR_CODE,
							PushConstants.ERROR_SUCCESS);
			// 返回内容
			final String content = new String(
					intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT));

			// 用户在此自定义处理消息,以下代码为demo界面展示用
			L.i("onMessage: method : " + method + ", result : " + errorCode
					+ ", content : " + content);
			paraseContent(context, errorCode, content);// 处理消息
			// 回调函数
			for (int i = 0; i < ehList.size(); i++)
				((EventHandler) ehList.get(i)).onBind(method, errorCode,
						content);

			// 可选。通知用户点击事件处理
		} else if (intent.getAction().equals(
				PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK)) {
			L.d(TAG, "intent=" + intent.toUri(0));
			
			String title = intent
					.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE);
			String content = intent
					.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT);
			for (int i = 0; i < ehList.size(); i++)
				((EventHandler) ehList.get(i)).onNotify(title, content);
			

			
		} else if (intent.getAction().equals(
				"android.net.conn.CONNECTIVITY_CHANGE")) {
			boolean isNetConnected = NetUtil.isNetConnected(context);
			for (int i = 0; i < ehList.size(); i++)
				((EventHandler) ehList.get(i)).onNetChange(isNetConnected);
		}
		
		
	}
	private void Parse(String message) {
		L.Debug("listener num ",""+ ehList.size());
		////******test******
		//		if(message.equals("0")){ PushMessageReceiver.MSG_ME++; }
		//		if(message.equals("1")){ PushMessageReceiver.MSG_COMMENT++; }
		//		if(message.equals("2")){ PushMessageReceiver.MSG_FUNS++; }	
		//		if(message.equals("3")){ PushMessageReceiver.MSG_NOTICE++; }

		L.Debug("****push message", ""+message);    
		isMsg = true;
		try {
			
			type = new JSONObject(message.toString()).getString("response").trim().toString();
			if(!type.equals(MSG_STR[0])&&!type.equals(MSG_STR[1])
					&&!type.equals(MSG_STR[2])&&!type.equals(MSG_STR[3])
					&&!type.equals(MSG_STR[4])&&!type.equals(MSG_STR[5])){
				isMsg = false;
			}


		} catch (JSONException e) {
			e.printStackTrace();
		}
		////*******做监听类型判断******
        L.Debug("****isMsg", ""+isMsg);
		 if(isMsg){
			    MsgHandle(message);
			    showNotify(message);
				Message handlerMsg = handler.obtainMessage(NEW_MESSAGE_STATE);
				handlerMsg.obj = message;
				handler.sendMessage(handlerMsg);				
	
		 }


	}
	/**
	 * 加载消息数目
	 */
    public void LoadMsgNum(){

    	SharePreferenceUtil mSpUtil =HSApplication.getInstance().getSpUtil();
    	PushMessageReceiver.MSG_ME = mSpUtil.getMSG_ME();
    	PushMessageReceiver.MSG_COMMENT = mSpUtil.getMSG_COMMENT();
    	PushMessageReceiver.MSG_FUNS = mSpUtil.getMSG_FUNS();
    	PushMessageReceiver.MSG_NOTICE = mSpUtil.getMSG_NOTICE();
    	PushMessageReceiver.MSG_FRIEND = mSpUtil.getMSG_FRIEND();
    	PushMessageReceiver.MSG_CHAT = mSpUtil.getMSG_CHAT();
    }
    /**
     * 消息保存处理
     * @param message
     */
	public void MsgHandle(String message){
		MsgState.push_state = -404;
		try {
			String type = new JSONObject(message.toString()).getString("response").trim().toString();
			if(type.equals("Mention")){
				
				String MeContent = new JSONObject(message.toString()).getString("Mention");
				JSONObject json = new JSONObject(MeContent);
				JSONObject share_json= json.getJSONObject("share");
				
				MeItem item = new MeItem();					
				item.setUserId(json.getString("uid"));
				item.setUserId2(share_json.getString("uid"));
				item.setType(share_json.getString("typeId"));
				item.setNick(share_json.getString("nickname"));
				item.setCommunityId(share_json.getString("communityid"));
				item.setTxt(share_json.getString("txt"));
				item.setDateLine(share_json.getString("dateline"));
				item.setLocation(share_json.getString("location"));					
				item.setName(json.getString("name"));
				
				if(json.optBoolean("pic")){
					item.setHeadPic(json.getString("headPic"));			
				}
				//HSApplication.msgHelper = new MessageHelper(HSApplication.mInstance);
				//HSApplication.msgHelper.insert(item.getUserId().toString());										
				HSApplication.getInstance().getMeMsgDB().saveMeMsg(item);	
				MsgState.push_state = MsgState.ME_MSG_STATE;
				tickerText = "最新"+ TYPE_STR[1];
				L.Debug("Mention run ok","");
			}

			
			if(type.equals("comment")){
				
				String MeContent = new JSONObject(message.toString()).getString("comment");
				JSONObject json = new JSONObject(MeContent);
				JSONObject share_json= json.getJSONObject("share");
				
				CommentItem item = new CommentItem();					
				item.setContent(json.getString("content"));
				item.setUserId(share_json.getString("uid"));
				item.setNick(share_json.getString("nickname"));
				//item.setType(share_json.getString("typeId"));
				item.setCommunityId(share_json.getString("communityid"));
				item.setTxt(share_json.getString("txt"));
				item.setDateLine(share_json.getString("dateline"));
				item.setLocation(share_json.getString("location"));					
				item.setName(json.getString("name"));
				if(json.optBoolean("pic")){					
					item.setHeadPic(json.getString("pic"));			
				}
									
				HSApplication.getInstance().getCommentMsgDB().saveCommentMsg(item);	
				MsgState.push_state = MsgState.COMMENT_MSG_STATE;
				tickerText = "最新"+ TYPE_STR[2];
				L.Debug("comment run ok","");
			}		
			
			if(type.equals("funs")){
				
				String MeContent = new JSONObject(message.toString()).getString("funs");
				JSONObject json = new JSONObject(MeContent);
				JSONObject share_json= json.getJSONObject("share");				
				PraiseItem item = new PraiseItem();					
				item.setUserId(share_json.getString("uid"));
				item.setNick(share_json.getString("nickname"));
				item.setType(share_json.getString("typeId"));
				item.setCommunityId(share_json.getString("communityid"));
				item.setTxt(share_json.getString("txt"));
				item.setDateLine(share_json.getString("dateline"));
				item.setLocation(share_json.getString("location"));					
				item.setName(json.getString("name"));
				
				if(json.optBoolean("pic")){
						item.setHeadPic(json.getString("pic"));												
				}
				HSApplication.getInstance().getPraiseMsgDB().savePraiseMsg(item);	
				MsgState.push_state = MsgState.FUNS_MSG_STATE;
				tickerText = "最新"+ TYPE_STR[3];
				L.Debug("funs run ok","");
			}

			
			if(type.equals("systemNotifications")){
				
				String MeContent = new JSONObject(message.toString()).getString("systemNotifications");
				JSONObject json = new JSONObject(MeContent);				
				NoticeItem item = new NoticeItem();					
				item.setContent(json.getString("content"));
				item.setDateLine(json.getString("time"));				
				HSApplication.getInstance().getNoticeMsgDB().saveNoticeMsg(item);
				MsgState.push_state = MsgState.NOTICE_MSG_STATE;
				tickerText = "最新"+ TYPE_STR[0];
				L.Debug("notice run ok","");
				
			}	
			
			if(type.equals("friendmsg")){
				//gender
				String MeContent = new JSONObject(message.toString()).getString("friendmsg");
				JSONObject json = new JSONObject(MeContent);
				JSONObject friend_json = json.getJSONObject("friend");
				RequestItem item = new RequestItem();
				item.setType(json.getString("type"));
				item.setUserId(friend_json.getString("id"));
				item.setMobile(friend_json.getString("mobile"));
				item.setNick(friend_json.getString("username"));
				//item.setGender(friend_json.getString("gender"));
				//item.setCompany(friend_json.getString("company"));
				//item.setTypeJob(friend_json.getString("zhiwu"));
				//item.setOccupation(friend_json.getString("occupation"));
				//item.setSupply(friend_json.getString("supply"));
				//item.setRequirement(friend_json.getString("requirement"));
				item.setTokenType(friend_json.getString("tokenType"));	
				if(json.optBoolean("headpic1")){					
					item.setPic("headpic1");
				}
				if(json.getString("type").equals("1")){
					L.Debug("type 1", "");
					//					for(int i=0;i<;i++){
					//						
					//					}
					HSApplication.getInstance().getRequestMsgDB().saveRequestMsg(item);	
					MsgState.push_state = MsgState.REQUEST_MSG_STATE;
				}
				if(json.getString("type").equals("2")){
					L.Debug("type 2", "");
					MsgState.push_state = MsgState.FD_LIST_MSG_STATE;
					try {
				
						String id = friend_json.getString("id");
						String mobile = friend_json.getString("mobile");
			            String nick = friend_json.getString("username");
			            L.Debug(" Add_Study_List id", id);
			            L.Debug(" Add_Study_List mobile", mobile);
			            L.Debug(" Add_Study_List username", nick);
						User user = new User();			
						user.setTelNum(mobile);
						user.setNick(nick);
						user.setId(id);
						Item08View.study_list.add(user);
						boolean isAdd = true;
						//过滤好友列表添加重复的人
				//						for(int i=0;i<Item08View.study_list.size();i++){
				//							if(id.equals(Item08View.study_list.get(i).getId())){
				//								isAdd = false;
				//								break;										
				//							}
				//						}
				//						if(isAdd==true){
				//							//if(Item08View.adapter!=null)
				//							//Item08View.adapter.notify();
				//						}
						
					} catch (JSONException e) {
						L.Debug("push Add_Study_List JSONException error", "");
						e.printStackTrace();
					}
					L.Debug("friendmsg run 2","");
				}
				
				tickerText = "最新"+ TYPE_STR[4];
				L.Debug("friendmsg run ok","");
			}

			if(type.equals("msg")){
				
				String MeContent = new JSONObject(message.toString()).getString("msg");
				JSONObject json = new JSONObject(MeContent);
				ChatMsgItem item = new ChatMsgItem();	
				String userId = json.getString("userid");
				item.setContent(json.getString("content"));
				item.setTime(json.getString("time"));
				item.setName(json.getString("name"));
				item.setUserid(userId);
				if(json.optBoolean("pic")){
					item.setPic(json.getString("pic"));						
				}
				item.setComMeg(true);
				HSApplication.getInstance().getChatMsgDB().saveChatMsg(userId,item);	
				
				//未读消息记录保存
				RecentItem recent = new RecentItem();
				recent.setUserId(json.getString("userid"));
				recent.setName(json.getString("name"));
				if(json.optBoolean("pic")){					
					recent.setHeadImg(json.getString("pic"));
				}
				recent.setMessage(json.getString("content"));
				HSApplication.getInstance().getRecentMsgDB().saveRecentMsg(recent);
				MsgState.push_state = MsgState.CHAT_MSG_STATE;
				tickerText = "最新"+ TYPE_STR[5];
				L.Debug("ChatMsg run ok","");
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
			L.Debug("推送 error", e.getMessage());
		}		
	}
	
    public static boolean isMatch(){
    	if(MsgState.state==MsgState.push_state){
    		return true;
    	}
    	return false;
    }	

    
	@SuppressWarnings("deprecation")
	public static void showNotify(String message) {
		mNewNum++;
		// 更新通知栏
		HSApplication application = HSApplication.getInstance();

		int icon = R.drawable.logo;

		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);

		notification.flags = Notification.FLAG_AUTO_CANCEL;//
		// 设置默认声音
		// notification.defaults |= Notification.DEFAULT_SOUND;
		// 设定震动(需加VIBRATE权限)
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.contentView = null;
		Intent intent = null;
		boolean isLogin = false;
		SharePreferenceUtil util = HSApplication.getInstance()
				.getSpUtil();
		isLogin = util.getLogin();
		if(isLogin){
			isPush = true;
			intent = new Intent(application, MainActivity.class);
		}else{
			intent = new Intent(application, WelcomeActivity.class);
		}
			
		PendingIntent contentIntent = PendingIntent.getActivity(application, 0,
				intent, 0);
		notification.setLatestEventInfo(HSApplication.getInstance(),
				application.getSpUtil().getNick() + " (" + mNewNum + "条新消息)",
				tickerText, contentIntent);

		application.getNotificationManager().notify(NOTIFY_ID, notification);// 通知一下才会生效哦

	}
	/**
	 * 处理登录结果
	 * 
	 * @param errorCode
	 * @param content
	 */
	private void paraseContent(final Context context, int errorCode,
			String content) {
		
		if (errorCode == 0) {
			String appid = "";
			String channelid = "";
			String userid = "";

			try {
				JSONObject jsonContent = new JSONObject(content);
				JSONObject params = jsonContent
						.getJSONObject("response_params");
				appid = params.getString("appid");
				channelid = params.getString("channel_id");
				userid = params.getString("user_id");
			} catch (JSONException e) {
				L.e(TAG, "Parse bind json infos error: " + e);
			}
			SharePreferenceUtil util = HSApplication.getInstance()
					.getSpUtil();
			util.setAppId(appid);
			util.setChannelId(channelid);
			util.setUserId(userid);

			L.Debug("push userid", util.getUserId());
		} else {
			if (NetUtil.isNetConnected(context)) {
				if (errorCode == 30607) {
					//L.showLong(context, "账号已过期，请重新登录");
					// 跳转到重新登录的界面
				} else {
					//L.showLong(context, "启动失败，正在重试...");
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							
							PushManager.startWork(context,
									PushConstants.LOGIN_TYPE_API_KEY,
									HSApplication.API_KEY);
						}
					}, 2000);// 两秒后重新开始验证
				}
			} else {
				T.showLong(context, R.string.net_error_tip);
			}
		}
	}

}



















